package com.linwen.javase.thread;

/**
 * @author : linwen
 * @date : 下午11:11 2021/2/22
 */
public class 生产者消费者问题 {
    public static void main(String[] args) {
        Shop shop = new Shop();
        Product p1 = new Product(shop);
        Thread t1 = new Thread(p1);
        Consume c1 = new Consume(shop);
        Thread t2 = new Thread(c1);
        t1.setName("生产者");
        t2.setName("消费者");
        t1.start();
        t2.start();
    }
}
class Shop{
    private int sumProduct=0;
    //生产
    public synchronized void produce() {
        if(sumProduct<20){
            sumProduct++;
            System.out.println(Thread.currentThread().getName()+"开始生产"+sumProduct);
            notify();
        }else{
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //消费
    public synchronized void consume() {
        if(sumProduct>0){
            System.out.println(Thread.currentThread().getName()+"开始消费"+sumProduct);
            sumProduct--;
            notify();
        }else{
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class Product implements Runnable{
    private Shop shop;

    public Product(Shop shop) {
        this.shop = shop;
    }

    @Override
    public void run() {
        while (true){
            shop.produce();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
class Consume implements Runnable{
    private Shop shop;

    public Consume(Shop shop) {
        this.shop = shop;
    }

    @Override
    public void run() {
        while (true){
            shop.consume();
            try {
                Thread.sleep(   100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }
}
